from app.api.gateio.modles import query_futures_tickers, query_user_positions
import time
from app import socketio
from threading import Event

def ticker_update_task(gate_key, gate_secret, settle, contract):
    stop_event = Event()
    while not stop_event.is_set():
        try:
            tickers = query_futures_tickers(gate_key, gate_secret, settle, contract)
            socketio.emit('update_tickers', tickers, namespace='/')
            time.sleep(0.5)
        except Exception as e:
            socketio.emit('error', {'message': f"Error updating tickers: {str(e)}"}, namespace='/')
            break  # 如果发生错误，中断循环
    return stop_event


def query_user_positions_task(gate_key, gate_secret, settle='usdt', holding=True, limit=100, offset=0):
    stop_event = threading.Event()

    def task():
        while not stop_event.is_set():
            try:
                response = query_user_positions(gate_key, gate_secret, settle, holding, limit, offset)
                socketio.emit('user_positions', {'data': response}, namespace='/')
                time.sleep(0.5)  # 每500毫秒请求一次
            except Exception as e:
                socketio.emit('error', {'message': f"Error querying user positions: {str(e)}"}, namespace='/')
                break  # 如果发生错误，中断循环

    thread = threading.Thread(target=task)
    thread.start()

    return stop_event

@socketio.on('start_ticker_update', namespace='/')
def handle_start_ticker_update(data):
    try:
        gate_key = data.get('gate_key')
        gate_secret = data.get('gate_secret')
        settle = data.get('settle', 'usdt')
        contract = data.get('contract', 'BTC_USDT')

        stop_event = ticker_update_task(gate_key, gate_secret, settle, contract)
        socketio.stop_event_ticker = stop_event
    except Exception as e:
        socketio.emit('error', {'message': f"Error starting ticker update: {str(e)}"}, namespace='/')

@socketio.on('stop_ticker_update', namespace='/')
def handle_stop_ticker_update():
    if hasattr(socketio, 'stop_event_ticker'):
        socketio.stop_event_ticker.set()

@socketio.on('query_user_positions', namespace='/')
def handle_query_user_positions(data):
    try:
        gate_key = data.get('gate_key')
        gate_secret = data.get('gate_secret')
        settle = data.get('settle', 'usdt')
        holding = data.get('holding', True)
        limit = data.get('limit', 100)
        offset = data.get('offset', 0)

        stop_event = query_user_positions_task(gate_key, gate_secret, settle, holding, limit, offset)
        socketio.stop_event_positions = stop_event
    except Exception as e:
        socketio.emit('error', {'message': f"Error querying user positions: {str(e)}"}, namespace='/')

@socketio.on('stop_query_user_positions', namespace='/')
def handle_stop_query_user_positions():
    if hasattr(socketio, 'stop_event_positions'):
        socketio.stop_event_positions.set()
